def merge_sort(arr):#排序函数
    # 如果数组只有一个元素或为空，已经有序，直接返回
    if len(arr) <= 1:
        return arr

    # 计算中间索引，将数组分为两半
    mid = len(arr) // 2
    left_half = arr[:mid]
    right_half = arr[mid:]

    # 递归地对两半进行归并排序
    left_sorted = merge_sort(left_half)
    right_sorted = merge_sort(right_half)

    # 合并两个有序的子数组
    return merge(left_sorted, right_sorted)


def merge(left, right):#合并函数
    # 创建一个空列表用于存储合并后的结果
    merged = []
    i = j = 0

    # 合并两个有序数组
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            merged.append(left[i])
            i += 1
        else:
            merged.append(right[j])
            j += 1

    # 将剩余部分添加到合并后的数组
    merged.extend(left[i:]) 
    merged.extend(right[j:]) 

    return merged


# 测试代码
if __name__ == "__main__":
    test_array = [38, 27, 43, 3, 9, 82, 19]
    print("原始数组:", test_array)
    sorted_array = merge_sort(test_array)
    print("排序后的数组:", sorted_array)